<?php

/**
 * Klasa reprezentująca abstrakcje nad sesję użytkownika.
 * Implemtuje interfejs ArrayAccess, żeby łatwiej przypisywać atrybuty.
 *
 */
class BasicUser_Core
{
	// bad..
	public static $_singleton = null;
	 
	protected $userAttributeStoragePrefix = 'user.';
	protected $credentialsStoragePrefix = 'credentials.';
	protected $authenticationStoragePrefix = 'auth.'; 	
	
	protected $storage = null;
	protected $credentials = array();
	protected $isAuthenticated = false;
	
	/**
	 * Uwierzytelnia użytkownika
	 * @param boolean $isAuthenticated
	 */
	public function setAuthenticated($isAuthenticated)
	{
		$this->set($this->authenticationStoragePrefix . 'is_authenticated', $isAuthenticated);		
	}
	
	/**
	 * Sprawdza czy użytkownik jest uwierzytelniony.
	 */
	public function isAuthenticated()
	{
		return $this->get($this->authenticationStoragePrefix . 'is_authenticated', false);		
	}
	
	/**
	 * Dodaj uprawnienie dla użytkownika
	 * @param string $name
	 */
	public function addCredential($name)
	{
		$credentials = $this->get($this->credentialsStoragePrefix, array());
		$credentials[] = $name;
		$this->set($this->credentialsStoragePrefix, $credentials);	
	}
	
	/**
	 * Czy użytkownik posiada uprawnienie/rolę.
	 * @param string $name
	 */
	public function hasCredential($name)
	{
		$credentials = $this->get($this->credentialsStoragePrefix, array());
		return in_array($name, $credentials);
	}
	
	public function removeCredential($name)
	{
		if ($this->hasCredential($name)) {
			$credentials = $this->get($this->credentialsStoragePrefix, array());
			unset($credentials[$name]);
			$this->set($this->credentialsStoragePrefix, $credentials);	
		}
	}
	
	public function clearCredentials()
	{
		$this->set($this->credentialsStoragePrefix, array());	
	}
	
	/**
	 * Ustaw atrybut w sesji.
	 * @param unknown_type $name
	 * @param unknown_type $value
	 */
	public function set($name, $value)
	{
		$this->storage->set($this->userAttributeStoragePrefix . $name, $value);
	}
	
	/**
	 * Pobierz atrybut.
	 * @param $name
	 * @param $default
	 */
	public function get($name, $default = null)
	{
		return $this->storage->get($this->userAttributeStoragePrefix . $name, $default);
	}
	
	/**
	 * Ustawienie kontenera na atrybuty
	 * @param mixed $storage Najcześciej Session::instance().
	 */
	public function setStorage($storage)
	{
		$this->storage = $storage;
	}
	
	public static function instance()
	{
		if (!isset(self::$_singleton))
		{
			self::$_singleton = new BasicUser();
			self::$_singleton->setStorage(Session::instance());	
		}
		return self::$_singleton;
	}
	
}